package com.idea.zd.sys.util.word;

import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

/**
 * 针对表格合并替换处理类
 * @author zzy
 */
public class WordToNewWordUtils {
    private final static Logger log = Logger.getLogger(WordToNewWordUtils.class);

    /**
     * 添加插入表格行及内容
     * @param document word文本
     * @param list 表格内容
     * @param staRow 开始列
     */
    public static void changeTable(CustomXWPFDocument document,List<String[]> list, int staRow){
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        if(0 != list.size()){
            //操作word中的表格
            for (int i = 0; i < tables.size(); i++) {
                //只处理行数大于等于2的表格，且不循环表头
                XWPFTable table = tables.get(i);
                if (null != list && 0 < list.size()){
                    insertTableRow(table, list,staRow,false,false,10);
                }
            }
        }
    }


    /**
     * 添加插入表格行及内容
     * @param document word文本
     * @param list 表格内容
     * @param staRow 开始列
     * @param horizontally 水平居中
     * @param vertical 垂直居中
     * @param fontSize 字体大小
     */
    public static void changeTable(CustomXWPFDocument document, List<String[]> list, int staRow,boolean horizontally,boolean vertical, int fontSize){
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        if(0 != list.size()){
            //操作word中的表格
            for (int i = 0; i < tables.size(); i++) {
                //只处理行数大于等于2的表格，且不循环表头
                XWPFTable table = tables.get(i);
                if (null != list && 0 < list.size()){
                    insertTableRow(table, list, staRow,horizontally,vertical,fontSize);
                }
            }
        }
    }

    /**
     * 遍历表格
     * @param rows 表格行对象
     * @param textMap 需要替换的信息集合
     */
    public static void eachTable(CustomXWPFDocument document, List<XWPFTableRow> rows , Map<String, Object> textMap){
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判断单元格是否需要替换
                if(checkText(cell.getText())){
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            Object ob = changeValue(run.toString(), textMap);
                            if (ob instanceof String){
                                run.setText((String)ob,0);
                            }else if (ob instanceof Map){
                                run.setText("",0);
                                Map pic = (Map)ob;
                                int width = Integer.parseInt(pic.get("width").toString());
                                int height = Integer.parseInt(pic.get("height").toString());
                                int picType = getPictureType(pic.get("type").toString());
                                byte[] byteArray = (byte[]) pic.get("content");
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                                try {
//                                    int ind = document.addPicture(byteInputStream,picType);
                                    document.createPicture(1, width , height,paragraph);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }



    /**
     * 为表格插入行
     * @param table 表格
     * @param daList 表格数据
     * @param fromRowSta 插入开始行
     * @param horizontally 是否水平居中
     * @param vertical 是否垂直居中
     * @param fontSize 字体大小
     */
    public static void insertTableRow(XWPFTable table, List<String[]> daList, int fromRowSta,boolean horizontally,boolean vertical, int fontSize){
        //创建行和创建需要的列
        for(int i = 0; i < daList.size()-1; i++){
            XWPFTableRow row = table.insertNewTableRow(fromRowSta);//在第fromRowSta行添加一个新行
            for(int c = 0; c<daList.get(i).length; c++){
                row.createCell();//添加第一个列
            }
        }

        //创建行,根据需要插入的数据添加新行，不处理表头
        for(int i = 0; i < daList.size(); i++){
            //获取i+fromRowSta行。进行数据添加
            List<XWPFTableCell> cells = table.getRow(i+fromRowSta).getTableCells();
            for(int j = 0; j < cells.size(); j++){
                XWPFTableCell cell = cells.get(j);

                //获取段落(第一个)
                cell.removeParagraph(0);
                XWPFParagraph xwpfParagraph =  cell.getParagraphArray(0);

                if(null == xwpfParagraph){
                    xwpfParagraph = cell.addParagraph();
                }

                //文本对象
                XWPFRun xr =  xwpfParagraph.createRun();

                //文字大小
                xr.setFontSize(fontSize);
                //文本内容
                xr.setText(daList.get(i)[j]);
                //垂直居中
                if(vertical){
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                }
                //水平居中
                if(horizontally){
                    xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
                }
                /*CTTc cttc = cell.getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
                cell.setText(daList.get(i)[j]);*/

            }
        }
    }


    /**
     * 判断文本中时候包含$
     * @param text 文本
     * @return 包含返回true,不包含返回false
     */
    public static boolean checkText(String text){
        boolean check  =  false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;
    }

    /**
     * 匹配传入信息集合与模板
     * @param value 模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static Object changeValue(String value, Map<String, Object> textMap){
        Set<Entry<String, Object>> textSets = textMap.entrySet();
        Object valu = "";
        for (Entry<String, Object> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = textSet.getKey();
            if(value.indexOf(key)!= -1){
                valu = value.replace(key, String.valueOf(textSet.getValue()));
                break;
            }
        }
        return valu;
    }

    /**
     * 将输入流中的数据写入字节数组
     * @param in
     * @return
     */
    public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(isClose){
                try {
                    in.close();
                } catch (Exception e2) {
                    System.out.println("关闭流失败");
                }
            }
        }
        return byteArray;
    }

    /**
     * 根据图片类型，取得对应的图片类型代码
     * @param picType
     * @return int
     */
    private static int getPictureType(String picType){
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if(picType != null){
            if(picType.equalsIgnoreCase("png")){
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            }else if(picType.equalsIgnoreCase("dib")){
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            }else if(picType.equalsIgnoreCase("emf")){
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            }else if(picType.equalsIgnoreCase("wmf")){
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    /**
     * 合并行
     * @param table
     * @param col 需要合并的操作的列
     * @param fromRow 开始行
     * @param toRow 结束行
     */
    public static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if ( rowIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 列合并
     * @param table
     * @param row 需要合并的操作的行
     * @param fromCell  开始列
     * @param toCell    结束列
     */
    public static void mergeCellHorizontally(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if ( cellIndex == fromCell ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 获取需要合并单元格的下标
     * @return
     */
    public static List<Integer[]> startEnd(List<String[]> daList){
        List<Integer[]> indexList = new ArrayList<Integer[]>();

        List<String> list = new ArrayList<String>();
        for (int i=0;i<daList.size();i++){
            list.add(daList.get(i)[0]);
        }
        Map<Object, Integer> tm = new HashMap<Object, Integer>();
        for (int i=0;i<daList.size();i++){
            if (!tm.containsKey(daList.get(i)[0])) {
                tm.put(daList.get(i)[0], 1);
            } else {
                int count = tm.get(daList.get(i)[0]) + 1;
                tm.put(daList.get(i)[0], count);
            }
        }
        for (Entry<Object, Integer> entry : tm.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            if (list.indexOf(key) != (-1)){
                Integer[] index = new Integer[2];
                index[0] = list.indexOf(key);
                index[1] = list.lastIndexOf(key);
                indexList.add(index);
            }
        }
        return indexList;
    }
}
